"""评估诊断路由"""
from fastapi import APIRouter, HTTPException, Body
from typing import Dict, Any
from datetime import datetime
from app.services.assessment_service import assessment_service

router = APIRouter()


@router.post("/assessment/initial")
async def initial_assessment(data: Dict[str, Any]):
    """初始能力评估（使用快速模拟测试）"""
    from app.services.mock_exam_service import mock_exam_service
    
    user_id = data.get("user_id", "user_001")
    exam_type = data.get("exam_type", "quick")  # 默认快速评估
    
    # 创建并提交快速测试
    exam = await mock_exam_service.create_mock_exam(user_id, exam_type)
    
    # 模拟答案（实际应该由用户提交）
    # 这里返回测试信息，前端需要引导用户完成测试
    return {
        "assessment_id": exam["exam_id"],
        "status": "created",
        "exam_info": {
            "exam_id": exam["exam_id"],
            "question_count": exam["question_count"],
            "time_limit": exam["time_limit"],
            "question_ids": exam["question_ids"]
        },
        "message": "请完成模拟测试以获取评估结果",
        "note": "评估完成后将自动计算知识阶段和各项能力分数"
    }


@router.post("/assessment/learning-style")
async def learning_style_diagnosis(user_id: str):
    """学习风格诊断"""
    # 使用推荐服务获取学习风格（模拟实现）
    from app.ai.recommendation_service import get_recommendation_service
    recommendation_service = get_recommendation_service()
    
    # 模拟学习风格诊断
    return {
        "user_id": user_id,
        "learning_style": "visual_analytical",
        "preferences": {
            "content_type": ["visual", "case_study"],
            "difficulty": "progressive",
            "feedback": "immediate"
        }
    }


@router.get("/assessment/weaknesses/{user_id}")
async def weakness_analysis(user_id: str):
    """薄弱环节分析"""
    # 模拟答题记录（实际应从数据库获取）
    from app.models.training import AnswerRecord
    answer_records = []  # 实际应该从数据库查询
    
    result = await assessment_service.analyze_weaknesses(user_id, answer_records)
    
    # 将WeaknessAnalysis对象转换为字典
    return {
        "user_id": result.user_id,
        "weak_areas": [
            {
                "area": area.get("area") if isinstance(area, dict) else getattr(area, "area", ""),
                "score": area.get("score") if isinstance(area, dict) else getattr(area, "score", 0),
                "priority": area.get("priority", "medium") if isinstance(area, dict) else getattr(area, "priority", "medium")
            }
            for area in result.weak_areas
        ],
        "recommendations": result.recommendations
    }


@router.post("/assessment/plan/{days}")
async def create_study_plan(days: int, data: Dict[str, Any] = Body(...)):
    """创建备考计划（180天/90天/60天）"""
    if days not in [180, 90, 60]:
        raise HTTPException(status_code=400, detail="不支持的天数，请选择180、90或60天")
    
    user_id = data.get("user_id", "user_001")
    
    # 尝试从测试结果获取当前水平（快速失败，不阻塞）
    current_level = 70.0  # 默认值
    try:
        from app.services.user_onboarding_service import user_onboarding_service
        test_result = user_onboarding_service.get_test_result(user_id)
        if test_result and test_result.get("test_result"):
            current_level = test_result["test_result"].get("accuracy", 70.0)
    except Exception as e:
        print(f"获取测试结果失败，使用默认值: {e}")
    
    # 创建计划（带超时保护）
    import asyncio
    try:
        plan = await asyncio.wait_for(
            assessment_service.create_study_plan(user_id, days, current_level=current_level),
            timeout=5.0  # 5秒超时
        )
    except asyncio.TimeoutError:
        raise HTTPException(status_code=500, detail="创建计划超时，请稍后重试")
    
    plan_id = f"plan_{days}_{user_id}"
    
    # 创建计划后，保存计划信息（快速失败，不阻塞）
    saved_to_redis = False
    try:
        from app.core.database import RedisClient
        redis = RedisClient.get_client()
        redis.ping()
        plan_key = f"plan:{plan_id}"
        redis.hset(plan_key, mapping={
            "plan_id": plan_id,
            "user_id": user_id,
            "duration_days": str(days),
            "daily_target_questions": str(plan["daily_target_questions"]),
            "created_at": datetime.now().isoformat()
        })
        redis.expire(plan_key, 86400 * 365)  # 保存1年
        saved_to_redis = True
        print(f"✅ [保存计划] 计划已保存到Redis: {plan_key}")
    except Exception as e:
        print(f"⚠️ Redis保存计划失败: {e}，将使用文件存储")
    
    # 如果Redis不可用，使用文件存储
    if not saved_to_redis:
        try:
            from app.services.file_storage_service import file_storage_service
            plan_key = f"plan:{plan_id}"
            plan_data = {
                "plan_id": plan_id,
                "user_id": user_id,
                "duration_days": str(days),
                "daily_target_questions": str(plan["daily_target_questions"]),
                "created_at": datetime.now().isoformat()
            }
            # 保存计划数据
            for field, value in plan_data.items():
                file_storage_service.hset(plan_key, field, value)
            file_storage_service.expire(plan_key, 86400 * 365)
            print(f"✅ [文件存储] 计划已保存到文件: {plan_key}")
        except Exception as e2:
            print(f"⚠️ 文件存储计划失败: {e2}")
    
    return {
        "user_id": user_id,
        "plan_id": plan_id,
        "duration_days": days,
        "daily_targets": {
            "study_hours": plan["daily_target_hours"],
            "questions": plan["daily_target_questions"],
            "review_time": 0.5
        },
        "phases": plan["phases"]
    }

